<template>
  <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
    <el-tab-pane label=详情 name="first">
      <over-view :data="formData" :key="activeName" v-if="activeName == 'first' && formData.devices" />

      <ContentWrap>
        <Descriptions title="详细信息" message="设备详细信息" :data="formData" :schema="schema" :columns="3" :key="formData.id" />
      </ContentWrap>

      <ContentWrap>
        <ElRow :gutter="24" justify="space-between">
          <ElCol :xl="12" :lg="12" :md="12" :sm="24" :xs="24" v-if="showMore">
            <ElCard shadow="hover" class="mb-20px">
              <template #header>
                <div class="card-header">

                  <el-select size="large" @change="loadIcmpData(formData.hostName)" v-model="pingStartTime"
                    placeholder="请选择" style="width: 30%">
                    <el-option v-for="dict in getIntDictOptionsString(DICT_TYPE.RRD_TIME)" :key="dict.value"
                      :label="dict.label" :value="dict.value" />
                  </el-select>
                  <!-- 自定义时间:
                  <el-date-picker size="large" v-model="pingStartTime" type="datetime" value-format="x"
                    placeholder="起始时间" />
                  -
                  <el-date-picker size="large" v-model="pingEndTime" type="datetime" value-format="x"
                    placeholder="截至时间" />

                  <el-button type="primary" plain @click="loadIcmpData(formData.hostName)">
                    <Icon icon="ep:view" /> 查询
                  </el-button> -->

                </div>
              </template>
              <Echart :options="lineOptions" :height="300" :key="formData.id" />
            </ElCard>
          </ElCol>

          <ElCol v-if="!showMore">
            <ElCard shadow="hover" class="mb-20px">
              <template #header>
                <div class="card-header">

                  <el-select size="large" @change="loadIcmpData(formData.hostName)" v-model="pingStartTime"
                    placeholder="请选择" style="width: 30%">
                    <el-option v-for="dict in getIntDictOptionsString(DICT_TYPE.RRD_TIME)" :key="dict.value"
                      :label="dict.label" :value="dict.value" />
                  </el-select>
                  <!-- 自定义时间:
                  <el-date-picker size="large" v-model="pingStartTime" type="datetime" value-format="x"
                    placeholder="起始时间" />
                  -
                  <el-date-picker size="large" v-model="pingEndTime" type="datetime" value-format="x"
                    placeholder="截至时间" />

                  <el-button type="primary" plain @click="loadIcmpData(formData.hostName)">
                    <Icon icon="ep:view" /> 查询
                  </el-button> -->

                </div>
              </template>
              <Echart :options="lineOptions" :height="300" :key="formData.id" />
            </ElCard>
          </ElCol>

          <ElCol :xl="12" :lg="12" :md="12" :sm="24" :xs="24" v-if="showMore">

            <ElCard title="CPU利用率" shadow="hover" class="mb-20px">
              <template #header>
                <div class="card-header">
                  <el-radio-group @change="currentUsageChange" v-model="currentUsage">
                    <el-radio-button label="3" value="3">设备温度</el-radio-button>
                    <el-radio-button label="1" value="1">CPU利用率</el-radio-button>
                    <el-radio-button label="2" value="2">内存利用率</el-radio-button>
                  </el-radio-group>
                </div>
              </template>

              <Echart :options="temOption" :height="300" v-if="currentUsage == '3'" :key="currentUsage" />
              <Echart :options="cpuOption" :height="300" v-else-if="currentUsage == '1'" :key="currentUsage" />
              <Echart :options="memOption" :height="300" v-else-if="currentUsage == '2'" :key="currentUsage" />
            </ElCard>
          </ElCol>

          <ElCol :xl="24" :lg="24" :md="24" :sm="24" :xs="24" v-if="showMore">
            <ElCard shadow="hover" class="mb-20px">
              <storage :devices="formData" v-if="formData.id" :key="formData.id" />
            </ElCard>
          </ElCol>

        </ElRow>
      </ContentWrap>

    </el-tab-pane>
    <el-tab-pane label=关系拓扑 lazy v-if="showMore">

      <ElCard shadow="hover" class="mb-20px">
        <template #header>
          <div class="card-header">
            <!-- <span>最近一小时ping延迟</span> -->
            <!-- <el-select v-model="value" clearable placeholder="请选择" size="large" style="width: 240px">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                  <el-button style="float: right; padding: 3px 0" type="text" @click="queryPing">按钮</el-button> -->
          </div>
        </template>
        <Echart :options="topoOption" :height="600" :key="formData.id" v-if="formData.id" />
      </ElCard>
    </el-tab-pane>
    <el-tab-pane label=功能表 lazy v-if="showMore">
      <other :devices="formData" v-if="formData.id" :key="formData.id" />
    </el-tab-pane>
    <el-tab-pane label=告警列表 lazy v-if="showMore">
      <alertLogIndex :data="formData" v-if="formData.id" :key="formData.id" />
    </el-tab-pane>
    <el-tab-pane label=设备日志 lazy v-if="showMore">
      <devicesLog :data="formData" v-if="formData.id" :key="formData.id" />
    </el-tab-pane>
    <el-tab-pane label=系统日志 lazy v-if="showMore">
      <sysLogIndex :data="formData" v-if="formData.id" :key="formData.id" />
    </el-tab-pane>
    <el-tab-pane label=自定义OID lazy v-if="showMore">
      <customerOidIndex :data="formData" />
    </el-tab-pane>
    <el-tab-pane label=补充OID lazy v-if="showMore">
      <OtherOidIndex :data="formData" />
    </el-tab-pane>
  </el-tabs>
</template>


<script setup lang="ts">
import overView from './overView.vue'
import { CompanypropertyApi, Companyproperty } from '@/api/business/companyproperty'
import { RrdDataApi } from '@/api/business/readData'
import { ElCard } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import storage from './storage.vue'
import other from './other.vue'
import { SensorsApi } from '@/api/business/sensors'
import devicesLog from '../devicesLog/index.vue'
import { LinksManualApi } from '@/api/business/linksManual'
import alertLogIndex from '../alertLog/index.vue'
import sysLogIndex from '../sysLog/index.vue'
import customerOidIndex from '../customOid/index.vue'
import OtherOidIndex from '../otheroid/index.vue'
import { getIntDictOptions, getIntDictOptionsString, DICT_TYPE } from '@/utils/dict'

// 当前时间的毫秒时间戳
const now = Date.now()

const pingStartTime = ref('now-1h') // 1小时前（毫秒）
const pingEndTime = ref('now')

const linkParams = reactive({
  localDeviceId: undefined,
})

const sensorsQueryParams = reactive({
  sensorDeleted: undefined,
  sensorClass: undefined,
  deviceId: undefined,
  pollerType: undefined,
  sensorOid: undefined,
  sensorCurrent: undefined,
})

const currentUsageChange = () => {
  console.log("currentusage", currentUsage.value);

}

const route = useRoute() // 路由
const router = useRouter() // 路由
const { t } = useI18n()

const value = ref('')

const currentUsage = ref(1)



const cpuOption = ref({
  series: [
    {
      type: 'gauge',
      radius: '90%',
      axisLine: {
        lineStyle: {
          width: 30,
          color: [
            [0.3, '#67e0e3'],
            [0.7, '#009688'],
            [1, '#fd666d']
          ]
        }
      },
      pointer: {
        itemStyle: {
          color: 'auto'
        }
      },
      axisTick: {
        distance: -30,
        length: 8,
        lineStyle: {
          color: '#fff',
          width: 2
        }
      },
      splitLine: {
        distance: -30,
        length: 30,
        lineStyle: {
          color: '#fff',
          width: 4
        }
      },
      axisLabel: {
        color: 'inherit',
        distance: 40,
        fontSize: 20
      },
      detail: {
        valueAnimation: true,
        formatter: '{value}%',
        color: 'inherit'
      },
      data: [
        {
          value: 0
        }
      ]
    }
  ]
});

const memOption = ref({
  series: [
    {
      type: 'gauge',
      startAngle: 180,
      endAngle: 0,
      center: ['50%', '60%'],
      radius: '100%',
      min: 0,
      max: 1,
      splitNumber: 8,
      axisLine: {
        lineStyle: {
          width: 6,
          color: [
            [0.25, '#7CFFB2'],
            [0.5, '#58D9F9'],
            [0.75, '#FDDD60'],
            [1, '#FF6E76']
          ]
        }
      },
      pointer: {
        icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
        length: '12%',
        width: 20,
        offsetCenter: [0, '-60%'],
        itemStyle: {
          color: 'auto'
        }
      },
      axisTick: {
        length: 12,
        lineStyle: {
          color: 'auto',
          width: 2
        }
      },
      splitLine: {
        length: 20,
        lineStyle: {
          color: 'auto',
          width: 5
        }
      },
      axisLabel: {
        color: '#464646',
        fontSize: 20,
        distance: -60,
        rotate: 'tangential',
        formatter: function (value) {
          // if (value === 0.875) {
          //   return 'Grade A';
          // } else if (value === 0.625) {
          //   return 'Grade B';
          // } else if (value === 0.375) {
          //   return 'Grade C';
          // } else if (value === 0.125) {
          //   return 'Grade D';
          // }
          return '';
        }
      },
      title: {
        offsetCenter: [0, '0%'],
        fontSize: 20
      },
      detail: {
        fontSize: 30,
        offsetCenter: [0, '-35%'],
        valueAnimation: true,
        // formatter: function (value) {
        //   return Math.round(value * 100) + '';
        // },
        formatter: '{value}%',
        color: 'inherit'
      },
      data: [
        {
          value: 0,
          name: '内存利用率'
        }
      ]
    }
  ]
});




const temOption = ref({
  series: [
    {
      type: 'gauge',
      center: ['50%', '60%'],
      startAngle: 200,
      endAngle: -20,
      min: 0,
      max: 60,
      splitNumber: 12,
      itemStyle: {
        color: '#FFAB91'
      },
      progress: {
        show: true,
        width: 30
      },
      pointer: {
        show: false
      },
      axisLine: {
        lineStyle: {
          width: 30
        }
      },
      axisTick: {
        distance: -45,
        splitNumber: 5,
        lineStyle: {
          width: 2,
          color: '#999'
        }
      },
      splitLine: {
        distance: -52,
        length: 14,
        lineStyle: {
          width: 3,
          color: '#999'
        }
      },
      axisLabel: {
        distance: -20,
        color: '#999',
        fontSize: 20
      },
      anchor: {
        show: false
      },
      title: {
        show: false
      },
      detail: {
        valueAnimation: true,
        width: '60%',
        lineHeight: 40,
        borderRadius: 8,
        offsetCenter: [0, '-15%'],
        fontSize: 60,
        fontWeight: 'bolder',
        formatter: '{value} °C',
        color: 'inherit'
      },
      data: [
        {
          value: 0
        }
      ]
    },
    {
      type: 'gauge',
      center: ['50%', '60%'],
      startAngle: 200,
      endAngle: -20,
      min: 0,
      max: 60,
      itemStyle: {
        color: '#FD7347'
      },
      progress: {
        show: true,
        width: 8
      },
      pointer: {
        show: false
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        show: false
      },
      axisLabel: {
        distance: -20,
        show: false,
        fontSize: 12
      },
      detail: {
        show: false
      },
      data: [
        {
          value: 0
        }
      ]
    }
  ]
});


const topoOption = ref({
  title: {
    text: '网络拓扑图',
    subText: '',
    left: 'center'
  },
  tooltip: {
    formatter: '{b}: {c}'
  },
  animationDurationUpdate: 1500,
  animationEasingUpdate: 'quinticInOut',
  series: [
    {
      type: 'graph',
      layout: 'force',
      symbolSize: 60,
      roam: true,
      // ====== 关键：优化节点标签样式 ======
      label: {
        show: true,
        position: 'bottom', // 文字显示在节点内部
        formatter: '{b}',   // 仅显示节点名称（{b} 代表节点名称）
        offset: [0, 0],
        rich: {
          name: {
            fontSize: 12,
            color: '#fff',
            backgroundColor: 'rgba(0,0,0,0.5)', // 半透明背景
            padding: [2, 4],      // 内边距
            borderRadius: 2,
            textShadow: '0 0 2px rgba(0,0,0,0.7)' // 添加阴影增强可读性
          }
        }
      },
      // ===================================
      edgeSymbol: ['none', 'none'],
      edgeSymbolSize: [0, 10],
      edgeLabel: {
        fontSize: 12,
        show: true,
        formatter: function (params) {
          return params.data.value;
        }
      },
      data: [],
      links: [],
      lineStyle: {
        opacity: 0.9,
        curveness: 0.1
      },
      force: {
        repulsion: 300,
        edgeLength: 150
      }
    }
  ]
});


const lineOptions = ref({
  title: {
    text: t('ping延迟/ms'),
    left: 'center'
  },
  xAxis: {
    data: [
    ],
    boundaryGap: false,
    axisTick: {
      show: false
    }
  },
  grid: {
    left: 20,
    right: 20,
    bottom: 20,
    top: 80,
    containLabel: true
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    },
    padding: [5, 10]
  },
  yAxis: {
    axisTick: {
      show: false
    }
  },
  legend: {
    data: ['ping延迟/ms'],
    top: 50
  },
  series: [
    {
      name: 'ping延迟/ms',
      smooth: true,
      type: 'line',
      data: [],
      animationDuration: 2800,
      animationEasing: 'cubicInOut',
      areaStyle: {
        color: '#009688', // 替换为你想要的颜色代码，比如 '#FFC125' 或者 'rgba(255, 193, 37, 0.5)'
        opacity: 0.2 // 可选，用于调整颜色的透明度
      },
    },

  ]
})



const deviceId = ref()

const schema = reactive([
  {
    field: 'hostName',
    label: 'IP地址'
  },
  {
    field: 'name',
    label: '名称'
  },
  {
    field: 'deviceTypeName',
    label: '设备类型'
  },
  {
    field: 'businessType',
    label: '业务类型'
  },
  {
    field: 'areaName',
    label: '区域'
  },
  {
    field: 'manufacturer',
    label: '厂商'
  },
  {
    field: 'model',
    label: '型号'
  },
  {
    field: 'serial',
    label: '序列号'
  },
  {
    field: 'manufactureDate',
    label: '生产日期'
  },
  {
    field: 'warrantyDate',
    label: '质保到期日期'
  },
  {
    field: 'location',
    label: '设备分布位置'
  },
  {
    field: 'createTime',
    label: '创建时间'
  }
])

const activeName = ref('first')
function handleClick(item, event) {
  // activeName
  console.log("tabs页面跳转", item.paneName, event)
  activeName.value = item.paneName
}
const formData = ref({
})

const showMore = ref(false);

const getDeviceDetail = async () => {
  formData.value = await CompanypropertyApi.getCompanyproperty(deviceId.value)
  showMore.value = formData.value.devices?.showMore

  cpuOption.value.series[0].data[0].value = formData.value.cpuUsage
  memOption.value.series[0].data[0].value = formData.value.memUsage

}

const getTemperature = async () => {
  sensorsQueryParams.deviceId = 136
  sensorsQueryParams.sensorClass = 'temperature'
  const data = await SensorsApi.getCurrent(sensorsQueryParams);
  console.log("温度", data);
  temOption.value.series[0].data[0] = data.sensorCurrent

}
const getLinksTop = async () => {
  linkParams.localDeviceId = 138
  const data = await LinksManualApi.getEChartsLinkData(linkParams);
  console.log("拓扑图", data);
  topoOption.value.series[0].data = data.data
  topoOption.value.series[0].links = data.links


}

const chartData = ref([])
const loading = ref(false)

// 使用示例
const loadIcmpData = async (deviceIp) => {
  try {
    const response = await RrdDataApi.getIcmpData(deviceIp, {
      // startTime: 'now-2h',
      // endTime: 'now'
      startTime: pingStartTime.value,// 2025-10-28 10:00:00 的秒级时间戳
      endTime: pingEndTime.value    // 2025-10-28 12:00:00 的秒级时间戳
    })

    console.log("返回值", response.dateTime);

    if (response.success) {

      lineOptions.value.series[0].data = response.data
      lineOptions.value.xAxis.data = response.dateTime


      // console.log('列名:', response.data.columnNames)
      // console.log('数据点数:', response.data.totalPoints)

      // 处理多列数据
      // response.data.dataPoints.forEach(point => {
      //   console.log(`时间: ${point.timestamp}`)
      //   console.log('指标数据:', point.metrics)
      // })

      // 显示统计信息
      // console.log('延迟统计:', response.data.additionalInfo.latencyStats)
      // console.log('丢包统计:', response.data.additionalInfo.packetLossStats)
    }
  } catch (error) {
    console.error('加载ICMP数据失败:', error)
  }
}

// 获取特定列数据用于图表
const loadChartDataForColumn = async (deviceIp, rrdFile, columnName) => {
  try {
    const response = await RrdDataApi.getColumnData(deviceIp, columnName, {
      rrdFile,
      startTime: 'now-24h',
      endTime: 'now'
    })

    if (response.data.success) {
      const chartData = response.data.dataPoints.map(point => ({
        x: new Date(point.timestamp * 1000),
        y: point.metrics[columnName]
      }))
      return chartData
    }
  } catch (error) {
    console.error('加载列数据失败:', error)
    return []
  }
}

// 自动刷新数据
const refreshInterval = ref(null)

const startAutoRefresh = () => {
  refreshInterval.value = setInterval(loadIcmpData, 60000) // 每分钟刷新
}

const stopAutoRefresh = () => {
  if (refreshInterval.value) {
    clearInterval(refreshInterval.value)
    refreshInterval.value = null
  }
}

// 获取文件列表
const loadRrdFiles = async (deviceIp: string) => {
  try {
    const response = await RrdDataApi.getRrdFiles(deviceIp)
    console.log('设备文件列表:', response.files)
  } catch (error) {
    console.error('获取文件列表失败:', error)
  }
}

onMounted(async () => {
  currentUsage.value = '3'
  deviceId.value = route.query.id
  activeName.value = 'first'
  await getDeviceDetail()
  getTemperature()
  getLinksTop()
  loadIcmpData(formData.value.hostName)
  startAutoRefresh()
  // loadRrdFiles(formData.value.hostName)
})

onUnmounted(() => {
  stopAutoRefresh()
})

</script>

<style scoped>
.alert-text {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 6px;
}

.alert-number {
  font-size: 28px;
  font-weight: bold;
  color: #696CFF;
}
</style>
